using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace TemperatureMicro
{
    class I2CLM75
    {
        private I2CDevice.Configuration config1;
        private int _id;
        private I2CDevice i2c;
        private I2CDevice.I2CTransaction[] I2CTransactionArray;
        private byte[] RegisterValue;
        private Configuration _fileAccess;
        private ServerAccess _serverAccess;

        public I2CLM75(string macAdress, Configuration fileSystem, ServerAccess server)
        {
            _fileAccess = fileSystem;
            _serverAccess = server;
            if (Configuration.SensorConfigFilePresent())
            {
                SetId(_fileAccess.GetId(DeviceType.sensor));
            }
            else
            {
                SetId(_serverAccess.registerDevice("Sensor", macAdress));
                _fileAccess.SaveSensorId(_id);
            }

            config1 = new I2CDevice.Configuration(0x48, 400);
            i2c = new I2CDevice(config1);
            I2CTransactionArray = new I2CDevice.I2CTransaction[1];
            RegisterValue = new byte[2];
            I2CTransactionArray[0] = I2CDevice.CreateReadTransaction(RegisterValue);
        }

        public void SetId(string id)
        {
            try
            {
                _id = Int32.Parse(id);
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
            }
        }

        public int GetId()
        {
            return _id;
        }

        public double ReadTemperature()
        {

            double measurementValue;

            if (i2c.Execute(I2CTransactionArray, 1000) == 0)
            {
                Debug.Print("Failed to perform I2C transaction");
                return -258;
            }
            else
            {
                if ((RegisterValue[1] & (1 << 7)) == 0)    //read first bit of 2nd byte, for float value
                {
                    measurementValue = RegisterValue[0];
                }
                else
                {
                    measurementValue = RegisterValue[0] + 0.5;
                }
            }

            Debug.Print("Measurement: " + measurementValue.ToString());
            _serverAccess.PostMeasurement(measurementValue, GetId());
            return measurementValue;
        }
    }
}
